package tcp;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args)throws Exception {
        //1.创建ServerSocket对象，指定端口
        ServerSocket server = new ServerSocket(9999);
        System.out.println("服务端开启，等待客户端连接");

        //2.响应客户端发送的请求
        Socket socket = server.accept();
        //3.获取传输数据的流对象
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        //4.传输数据
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        String msg = new String(bytes, 0, len);
        String hostAddress = socket.getInetAddress().getHostAddress();
        System.out.println("读取到" + hostAddress + "发来的消息:" + msg);

        outputStream.write("你也好".getBytes());

        //5.关闭释放资源
        socket.close();
        server.close();

    }
}
